import React, {useRef, useState} from 'react';
import {PageContainer} from "@ant-design/pro-layout"
import {Button, message, Popconfirm} from "antd";
import ProTable from '@ant-design/pro-table';
import {DeleteOutlined, EditOutlined, PlusOutlined} from '@ant-design/icons';
import CreateOrEdit from "@/pages/Label/components/CreateOrEdit";
import {getLabelData,delLabelList} from "@/services/label";
const Index = () => {
  const [isModalVisible,setIsModalVisible] = useState(false)

  const [editId,setEditId] = useState(undefined)


  //表格自动刷新
  const refs = useRef();
  //表格字段
  const columns=[
    {
      title:"ID",
      dataIndex: 'id',
      hideInSearch: 'false',
    },
    {
      title:"名称",
      dataIndex: 'name',
    },
    {
      title: "排序",
      dataIndex: 'order',
      hideInSearch: 'false',

    },
    {
      title:'操作',
      render: (_,record) => {
        return <div>
          <Popconfirm title="你确定要删除吗？" onConfirm={()=>{return delLabel(record.id)}} okText='确认'>
            <Button type="danger" shape="circle"  icon={<DeleteOutlined />} />
          </Popconfirm>&nbsp;&nbsp;
          <Button type="primary" shape="circle" onClick={ async ()=>showModal(true,record.id) }  icon={<EditOutlined />} />&nbsp;&nbsp;
        </div>
      }
    },
  ]
  //模态框
  const showModal = (show,editId = undefined) => {
    setIsModalVisible(show)
    setEditId(editId)
  }
  //获取标签
  const getLabels = async (params)=>{
    const getLabelLink = await getLabelData(params)
    return{
      data:getLabelLink.data,
      success:true,
    }
  }
  //删除标签
  const delLabel = async (id) =>{
    const res = await delLabelList(id)
    if (res.status == null){
      message.success("删除成功")
      setIsModalVisible(false)
      refs.current.reload();
    }else{
      message.error('删除失败')

    }
  }
  return (
    <PageContainer>
      <ProTable
        actionRef={refs}
        columns={columns}
        rowKey="id"
        request={async (params= {}) => getLabels(params) }
        search={{
          labelWidth: 'auto',
          collapseRender:false,
        }}
        dateFormatter="string"
        headerTitle="标签管理"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} onClick={()=> showModal(true)}  type="primary">
            新建
          </Button>,

        ]}
      />
      {
        isModalVisible ?
         <CreateOrEdit
            showModal={showModal}
            visible={isModalVisible}
            editId={editId}
            refs={refs}
          />:''
      }
    </PageContainer>
  );
}


export default Index;
